package io.webchat.interceptor;

import com.alibaba.fastjson.JSON;
import io.webchat.annotation.Login;
import io.webchat.exception.RRException;
import io.webchat.utils.Constant;
import io.webchat.utils.JwtUtils;
import io.webchat.wdzl.pojo.Token;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;


/**
 * 权限(Token)验证
 *
 */
@Component

public class AuthorizationInterceptor extends HandlerInterceptorAdapter {


    @Autowired
    JwtUtils jwtUtils;


    @Autowired
    RedisTemplate redisTemplate;


    public static final String USER_KEY = "userId";


    List<String> notInterceptUrl = new ArrayList<>();

    static {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }

        //token为空
        if(StringUtils.isBlank(token)){
            throw new RRException("token不能为空",10001);
        }
        //查询token信息
        String userId = jwtUtils.getUserId(token);

        String  tokenVo =redisTemplate.opsForValue().get(Constant.LOGON_TOKEN+userId).toString();
        Token tokenEntity = JSON.parseObject(tokenVo,Token.class);
        if(tokenEntity == null || tokenEntity.getExpireTime() < System.currentTimeMillis() || !tokenEntity.getToken().equals(token)
                || notInterceptUrl.contains(request.getRequestURI())){
            throw new RRException("token失效，请重新登录",10001);
        }
        //设置userId到request里，后续根据userId，获取用户信息
       request.setAttribute(USER_KEY, userId);
        return true;
    }
}
